import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
// 引用elementUI的样式库
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'

import 'font-awesome/css/font-awesome.min.css'
import './common/js/permission.js'

// 配置Axios
import axios from "axios"
axios.defaults.baseURL = "http://localhost:8080"
Vue.prototype.$http = axios


Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})
//处理页面刷新动态路由失效问题
initIndexRouters();
function initIndexRouters(){
    if(!localStorage.menus){
        return;
    }
    //防止重复配置路由：5就是main.js中路由的个数 - 如果你的静态路由是6个这里要写成6
    if(router.options.routes.length>8){
        return;
    }
    let menus = localStorage.getItem('menus');
    menus = JSON.parse(menus);
    let tempRouters = [];
    menus.forEach(menu=>{
        let indexRouter = {
            path: '/',
            iconCls: menu.icon,
            name: menu.name,
            component: resolve => require(['@/views/Home'], resolve),
            children: []
        }
        menu.children.forEach(cMenu=>{
            let cr = {
                path: cMenu.url,
                name: cMenu.name,
                component: resolve => require(['@/views/'+cMenu.component], resolve)
            }
            indexRouter.children.push(cr)
        })
        tempRouters.push(indexRouter)
        router.options.routes.push(indexRouter)
    })
    //动态路由配置
    router.addRoutes(tempRouters);
}

/*======================我们自己的拦截器开始*/

//1.路由拦截器，就是用户点击路由访问的时候，我们能否让他访问，其实就是登录拦截的意思
router.beforeEach((to, from, next) => {
  console.log("111111111111111");
  if (to.path == '/login' || to.path == '/shopRegister') {
      if (localStorage.getItem("token")){
          // 1.清除localstorage中的用户数据
          localStorage.removeItem("token");
          localStorage.removeItem("logininfo");
          localStorage.removeItem("menus");
          localStorage.removeItem("permissions");
          // 2.清除浏览器路由缓存
          location.reload();
      }
    // 放行
    next();
    return;
  }
  let token = localStorage.getItem('token');
  if (token) {
    next();
  } else {
    next({ path: '/login' })
  }
})

//2.配置axios前置拦截器，作用是让所有axios请求携带token，后台需要token校验是否登录
axios.interceptors.request.use(config=>{
  console.log("222222222");
  // 2.1.
  let token =  localStorage.getItem("token");
  // 2.2.如果token不为null，那么设置到请求头中，此处哪怕为null，我们也不进行处理，因为后台会进行拦截
  if(token){//从缓存中获取到token
    // 设置到请求头中
      config.headers['token']=token;
  }
  // 2.3.放行
  return config;
},error => {
  Promise.reject(error);
})

//3.配置axios后置拦截器，作用是为了得到后端的拦截器响应结果
//  前端需要知道用户是否登录，如果响应是success=false&resultObj=noLogin那么说明用户未登录，直接跳转到登录页面
axios.interceptors.response.use(result=>{
  console.log("4444444444444");
  // 3.1.获取到后端的响应结果
  let data = result.data;
  console.log(data);
  // 3.2.判断如果后端响应是success=false&resultObj=noLogin，那就说明在后端拦截器中被拦截下来了，那么跳转到登录页面
  if(!data.success && data.message==="noLogin"){
    // 跳转登录页面
    router.push({path: '/login'});
  }
    if(!data.success && data.message==="noPermission"){
        // 跳转登录页面
        router.push({path: '/noPermission'});
    }
  // 3.3.放行
  return result;
},error => {
  Promise.reject(error);
})





/*======================我们自己的拦截器结束*/


// mock引入代码
/*import Mock from './mock'
Mock.bootstrap();*/




//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

